<?php
namespace lib;

class Cache{

    /**
     * @var
     */
    protected static $conf = [
        'path'  => ROOT_PATH . 'cache/',
        'suffix'    => 'che'
    ];

	/**
	 * 初始化
	 */
	public static function init(){
		is_dir(self::$conf['path']) || mkdir(self::$conf['path'], 0755, true);
	}

    /**
     * 存储数据
     * @param $key
     * @param $content
     * @param $options
     * @return bool|string
     */
    public static function save($key, $content, $options = []){
    	self::init();
    	self::$conf = array_merge(self::$conf, $options);
        $filename = self::filename($key);
        if(file_put_contents($filename, $content)){
            return $filename;
        }
        return false;
    }

    /**
     * 设置缓存
     * @param $key
     * @param $val
     * @param $expire
     * @return bool
     */
    public static function set($key, $val, $expire = 0){
	    self::init();
        $filename = self::filename($key);
        $data = sprintf('%012d', $expire) . serialize($val);
        if(file_put_contents($filename, $data)){
            return $filename;
        }
        return false;
    }

    /**
     * 获取缓存
     * @param $key
     * @return bool
     */
    public static function get($key){
	    self::init();
        $filename = self::filename($key);
        if(file_exists($filename)){
            $data = file_get_contents($filename);
            $expire = (int)substr($data, 0, 12);
            if($expire !== 0) {
                if (time() > ($expire + (int)filemtime($filename))) {
                    unlink($filename);
                    return false;
                }
            }
            return unserialize(substr($data, 12));
        }
        return false;
    }

    /**
     * 获取缓存文件名
     * @param $key
     * @return string
     */
    public static function filename($key){
	    self::init();
        return self::$conf['path'] . md5($key) . '.' . self::$conf['suffix'];
    }

}